#-*- coding:utf-8 -*-
from collections import namedtuple
class Entity(object):
    def __init__(self,class_name,columns,**kwargs):
        super(Entity,self).__init__()
        #去除空格
        _columns=[i.strip() for i in columns.split(" ") if i.strip()]
        _columns.extend(kwargs.keys())
        columns=list(set(_columns))
        entity=namedtuple(class_name,columns)
        self._entity=entity(**kwargs)
    #该方法可以拦截对对象属性的所有访问企图，当属性被访问时，自动调用该方法（只适用于新式类）。因此常用于实现一些访问某属性时执行一段代码的特性。
    def __getattribute__(self, key):
        entity=super(Entity, self).__getattribute__("_entity")
        try:
            return super(Entity, self).__getattribute__(key)
        except:
            return getattr(entity,key)
    def __setattr__(self, key, value):
        if key=="_entity":
            super(Entity,self).__setattr__("_entity",value)
            return
        entity=super(Entity, self).__getattribute__("_entity")
        try:
            entity.__setattr__(key,value)
        except:
            super(Entity,self).__setattr__(key,value)
   #__getattr__方法的自动执行，需要满足两个条件：一是访问对象属性；二是触发AttributeError异常。代码示例如下：
   # def __getattr__(self, item):

# if __name__=='__main__':
#     user={"name":"aaa","age":23}
#     entity=Entity("user","",**user)
#     print(entity)
#     print(entity.name)
#     print(entity.age)
#     entity.aa='b'
#     print(entity.aa)